<template>
  <el-upload
    class="tag-upload"
    ref="upload"
    :action="url"
    :headers="headers"
    :multiple="multiple"
    :data="data"
    :name="name"
    :drag="drag"
    :on-success="successFun"
    :on-error="errorFun"
    :before-upload="beforeUpload"
    :before-remove="beforeRemove"
    :on-change="changeFun"
    :file-list="fileListNow"
    :list-type="listType"
    :on-preview="clickFun"
    :auto-upload="auto"
  >
    <slot name="button">
      <template v-if="drag">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
      <el-button v-else size="small" type="primary">点击上传</el-button>
    </slot>
    <template slot="tip">
      <div class="el-upload__tip" :class="{ uploadcard: listType === 'picture-card', text: listType === 'text' }">
        <slot name="tip"></slot>
      </div>
    </template>
  </el-upload>
</template>

<script>
import utils from '@/plugins/utils'
export default {
  name: 'tag-upload',
  props: {
    action: {
      type: String,
      default: 'stg/stgFileUpload'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
    name: {
      type: String,
      default: 'file'
    },
    drag: {
      type: Boolean,
      default: false
    },
    fileList: {
      type: Array,
      default: () => {
        return []
      }
    },
    listType: {
      type: String,
      default: 'text'
    },
    oldId: {
      type: String,
      default: 'fileId'
    },
    fileLimit: {
      type: Object,
      default: () => {
        return {}
      }
    },
    auto: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    url() {
      return this.$ajax.setUrl(this.action)
    }
  },
  data() {
    return {
      headers: {
        'auth-token': window.localStorage.getItem('token')
      },
      fileListNow: [],
      progressList: []
    }
  },
  created() {
    this.fileListNow = this.fileList
  },
  watch: {
    fileList() {
      this.fileListNow = this.fileList
    }
  },
  methods: {
    successFun(response, file, fileList) {
      if (response.code === '0') {
        file.fileId = response.data.fileId
        this.$emit('uploadFun', {
          fileId: response.data.fileId,
          file: file,
          fileList: fileList
        })
      } else {
        this.fileListNow = fileList.filter(item => item.uid !== file.uid)
        this.$message.error(response.data || response.msg)
      }
      this.removeProgress(file.uid)
    },
    errorFun(err, file) {
      if (err.status === 401) {
        this.$message.error('登录失效，请重新登录')
        utils.clearLoginInfo()
        utils.sysOut()
      } else if (err.status === 403) {
        this.$message.error('没有进行该操作的权限')
      } else {
        this.$message.error('连接出错')
      }
      this.removeProgress(file.uid)
    },
    beforeUpload(file) {
      if (this.fileLimit.type) {
        let index = this.fileLimit.type.indexOf(file.type)
        if (index === -1) {
          this.$message.error(this.fileLimit.typeMsg || '不支持的文件类型')
          file._limitError = true
          return false
        }
      }
      file._new = true
      this.progressList.push(file.uid)
    },
    removeProgress(uid) {
      var index = this.progressList.indexOf(uid)
      if (index !== -1) {
        this.progressList.splice(index, 1)
      }
    },
    beforeRemove(file) {
      if (!file.raw || !file.raw._limitError) {
        var p = this.$confirm('确认要删除【' + file.name + '】？')
          .then(() => {
            let messageBox = document.getElementsByClassName('el-message-box__wrapper')
            messageBox[0].focus() // 防止按空格键重复确定
            if (file.status === 'success') {
              if (file.raw && file.raw._new) {
                this.$emit('removeFun', {
                  type: 'new',
                  fileId: file.fileId
                })
              } else {
                this.$emit('removeFun', {
                  type: 'old',
                  fileId: file[this.oldId]
                })
              }
            } else {
              this.removeProgress(file.uid)
            }
          })
          .catch(() => {
            p.reject()
          })
        return p
      }
    },
    changeFun(file, fileList) {
      this.$emit('changeFun', {
        file: file,
        fileList: fileList
      })
    },
    getProgress() {
      return this.progressList.length > 0
    },
    clickFun(file) {
      this.$confirm('是否下载文件【' + file.name + '】？')
        .then(() => {
          let messageBox = document.getElementsByClassName('el-message-box__wrapper')
          messageBox[0].focus() // 防止按空格键重复确定
          this.$dlFile(file.fileId)
        })
        .catch(() => {})
    },
    submit() {
      this.$refs.upload.submit()
    }
  }
}
</script>

<style lang="scss">
.tag-upload {
  line-height: 16px;
}
</style>
